<?php
class Delivery_Model_DbTable_Direcciones
	extends Delivery_Model_DbTable_Abstract

{
	protected $_name = 'direcciones';
	protected $_primary = 'idDireccion';
	
	public function insert( $direccion ){
		
		$data = array (
			'calle'		=> $direccion->calle,
   			'numero'	=> $direccion->numero,
   			'barrio'	=> $direccion->barrio,
   			'idCiudad'	=> $direccion->idCiudad,
			'punto'		=> new Zend_Db_Expr("GeomFromText('POINT($direccion->latitud $direccion->longitud)')"),
		    'fullName'	=> $direccion->fullName
		
   		);
		
		$data = $this->_fecha( $data, true, false);
		
		return parent::insert( $data );	
	}
	
	public function select(){
	
		return  
			parent::select( self::SELECT_WITHOUT_FROM_PART)
					->from( $this->_name, array('idDireccion', 'calle', 'numero', 'barrio', 'idCiudad', 'fullName'))					
					->columns(array('latitud'=>'X(punto)'))
					->columns(array('longitud'=>'Y(punto)'));
	
	}
	
	public function getById( $idDireccion ){
		
		return 
			$this->_db->fetchRow(
				$this->select()->where('idDireccion = ?', $idDireccion)
			);
	}
	
	/**
	 * @param array $ids
	 * @return array:
	 */
	public function getByIds( $ids )
	{
		return $this->getAdapter()->fetchAll(
			$this->select()->where( 'idDireccion IN (?)', $ids, Zend_Db::INT_TYPE),
			null,
			Zend_Db::FETCH_ASSOC
		);		
	}
	
	public function getByAddress( $calle, $numero, $idCiudad, $barrio = null ){

	    $select = $this->select()
					->where('calle = ?', $calle)
					->where('numero = ?', $numero, Zend_Db::INT_TYPE)
					->where('idCiudad = ?', $idCiudad, Zend_Db::INT_TYPE);
	    
        if( $barrio ){
            $select->where('barrio = ?', $barrio);
        }					
					
		return $this->_db->fetchRow( $select );
	}
	
	public function search( $string ){

		$string = str_replace(" ", '', $string);
		$string = str_replace(",", '', $string);
		$string = str_replace("-", '', $string);
		
		$select = $this->select()
		            ->setIntegrityCheck(false)
					->joinUsing('ciudades', 'idCiudad');
		
		$sql = $select->assemble();
		$sql.= " WHERE CONCAT(calle, numero, IF (barrio IS NULL, '', barrio), ciudades.nombre) = ?";
		
		$sql = $this->_db->quoteInto($sql, $string);
		
		return $this->_db->fetchRow( $sql );
	}
	
	public function ciudades(){
	
		$select = parent::select( self::SELECT_WITHOUT_FROM_PART)
					->from( $this->_name, array('idCiudad'))
					->joinUsing( 'negocios', 'idDireccion', array())
					->distinct();
		return 
			$this->_db->fetchCol(
				$select
			);
	
	}
	
	
}